#!/usr/bin/python3

import joblib
import numpy
numpy.random.seed(42)
from sklearn import tree

### The words (features) and authors (labels), already largely processed.
### These files should have been created from the previous (Lesson 10)
### mini-project.

words_file = "../text_learning/your_word_data.pkl" 
authors_file = "../text_learning/your_email_authors.pkl"

# words_file = "word_data_overfit.pkl" 
# authors_file = "email_authors_overfit.pkl"

word_data = joblib.load( open(words_file, "rb"))
authors = joblib.load( open(authors_file, "rb") )


### test_size is the percentage of events assigned to the test set (the
### remainder go into training)
### feature matrices changed to dense representations for compatibility with
### classifier functions in versions 0.15.2 and earlier
from sklearn.model_selection import train_test_split
features_train, features_test, labels_train, labels_test = train_test_split(word_data, authors, test_size=0.1, random_state=42)

from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, stop_words='english')
features_train = vectorizer.fit_transform(features_train)
features_test  = vectorizer.transform(features_test).toarray()


### a classic way to overfit is to use a small number
### of data points and a large number of features;
### train on only 150 events to put ourselves in this regime
features_train = features_train[:150].toarray()
labels_train   = labels_train[:150]


### your code goes here
classifier = tree.DecisionTreeClassifier()
classifier.fit(features_train, labels_train)
acc = classifier.score(features_test, labels_test) 
print("accuracy of tree is", acc)

print(classifier.feature_importances_)
vocab = vectorizer.get_feature_names_out()

def get_important_word(features, importance):
    assert(len(features) == len(importance))
    most_important = float(0)
    mi_word  = str()
    mi_index = 0
    for i in range(len(features)):
        if most_important < importance[i]:
            most_important = importance[i]
            mi_index = i
    mi_word = features[mi_index]
    return most_important, mi_index

weight, index = get_important_word(
    vocab, classifier.feature_importances_ )
print(weight, index, vocab[index])

def get_relevant_words(importances, threshhold=0.2):
    relevant = []
    for i in range(len(importances)):
        if importances[i] > threshhold:
            relevant.append(i)
    return relevant

indices = get_relevant_words(classifier.feature_importances_)
print(len(indices))
